/**
 * 详情对话框
 */
var TaskInfoDlg = {
    data: {
        planId: "",
        title: "",
        type: "",
        remark: "",
        status: "",
        worker: "",
        reviewWorker: "",
        startTime: "",
        endTime: "",
        createTime: "",
        updateTime: ""
    }
};

layui.use(['form', 'admin', 'ax', 'jquery', 'steps', 'laydate', 'func'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var func = layui.func;

    var materialList = [];
    var resultData;
    var recordResult;
    var selectOthers = [];
    var selectMaterials = [];

    var selectWorker;
    var selectReviewWorker;


    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //加载信息
    loadResultData();

    function loadResultData() {

        //获取材料
        loadMaterialList();
        //获取详情信息，填充表单
        loadNetWordData();
        //记录
        loadRecordData();
        //界面
        loadUI();
        // 加载记录
        loadTaskRecord();
        // // 人员
        loadWorkerList();
        // 审核人员
        loadReviewWorkerList();


    }

    function loadRecordData() {
        if (!Feng.isUndefined(Feng.getUrlParam("taskId"))) {

            var type = resultData.type;
            var taskId = resultData.taskId;
            var reportDate = Feng.getNowDate();
            var param = 'taskId=' + taskId + "&" + "type=" + type + "&" +  "reportDate=" + reportDate;
            var ajax = new $ax(Feng.ctxPath + "/api/taskRecord/detail?" + param);
            var result = ajax.start();
            recordResult = result.data;
            resultData.status = recordResult.status;
            resultData.reviewStatus = recordResult.reviewStatus;
            resultData.taskRecordId = recordResult.taskRecordId;
            form.val('taskForm', resultData);

            // 执行人跟审核人
            if (!Feng.isUndefined(recordResult.worker)){
                selectWorker = recordResult.worker;
            }
            if (!Feng.isUndefined(recordResult.reviewWorker)){
                selectReviewWorker = recordResult.reviewWorker;
            }
            //反选任务
            if (!Feng.isUndefined(recordResult.record)) {
                var dict = JSON.parse(recordResult.record);
                var m = dict['materiel'];
                var o = dict['other'];
                if (!Feng.isUndefined(m)) {
                    selectMaterials = JSON.parse(m);
                }
                if (!Feng.isUndefined(o)) {
                    selectOthers = JSON.parse(o);
                }
            }
        }
    }

    function loadNetWordData() {
        if (!Feng.isUndefined(Feng.getUrlParam("taskId"))) {
            var ajax = new $ax(Feng.ctxPath + "/api/task/detail?taskId=" + Feng.getUrlParam("taskId"));
            var result = ajax.start();
            resultData = result.data;
            form.val('taskForm', resultData);

            selectWorker = resultData.worker;
            selectReviewWorker = resultData.reviewWorker;
        }
    }

    function loadUI() {
        //
        var taskType = "普通任务";
        if (resultData.type === 1){
            taskType = "日任务";
        }else if (resultData.type === 2){
            taskType = "周任务";
        }else if (resultData.type === 3){
            taskType = "月任务";
        }
        //
        var statusDesc = "未执行";
        if (recordResult.status === 0){
            statusDesc = "未执行";
        }else if (recordResult.status === 1){
            statusDesc = "执行完成";
        }else if (recordResult.status === 2){
            statusDesc = "取消执行";
        }
        //
        var reviewDesc = "未审核";
        if (recordResult.reviewStatus === 0){
            reviewDesc = "未审核";
        }else if (recordResult.reviewStatus === 1){
            reviewDesc = "审核完成";
        }else if (recordResult.reviewStatus === 2){
            reviewDesc = "取消审核";
        }


        $("#taskType").html("类型:" + taskType);
        $("#taskDate").html("日期:" + recordResult.reportDate);
        $("#taskStatus").html("执行状态:" + statusDesc);
        $("#taskReviewStatus").html("审核状态:" + reviewDesc);

        //
        if(recordResult.reviewStatus === 1 && recordResult.status === 1){
            $("#comfireButton").addClass("hide");
        }
    }

    //加载物料

    function loadMaterialList() {

        var ajax = new $ax(Feng.ctxPath + "/api/materiel/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].materielId;
                var specs = data.data[i].specs;
                var number = data.data[i].number;
                var unit = data.data[i].unit;
                var dict = {"value": value, "name": name, "specs": specs, "maxNumber": number, "unit": unit};
                materialList.push(dict);
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    function loadTaskRecord() {

        //日任务加载

        if (Feng.isArray(selectMaterials)) {
            for (var a = 0; a < selectMaterials.length; a++) {
                var materiel = selectMaterials[a];
                addTaskMaterielItem(a, materiel.name + '', materiel.number);
            }
        }
        if (Feng.isArray(selectOthers)) {
            for (var b = 0; b < selectOthers.length; b++) {
                var other = selectOthers[b];
                addTaskOtherItem(b, other);
            }
        }
    }

    //=========== 加载工作人员 ========== //

    function loadWorkerList() {

        $("#workerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (value === selectWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectWorker) && value !== selectWorker) {
                    selectWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#workerSelect").append('<option value="' + value + '"  ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(workerSelect)', function (data) {
        selectWorker = data.value;
    });

    function loadReviewWorkerList() {

        $("#reviewWorkerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (value === selectReviewWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectReviewWorker) && value !== selectReviewWorker) {
                    selectReviewWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#reviewWorkerSelect").append('<option value="' + value + '"  ' + selected + '>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    form.on('select(reviewWorkerSelect)', function (data) {
        selectReviewWorker = data.value;
    });


    //任务
    function addTaskOtherItem(index, value) {

        var i = selectOthers.length;
        if (index !== null) {
            i = index;
        }
        if (value === null) {
            value = "";
        }
        var selectClassName = 'other_name_' + i + '_day';

        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md8"><label class="layui-form-label">操作</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + selectClassName + ' name=' + selectClassName + ' type="text" value="' + value + '" placeholder="填写操作" class="layui-input"/>' +
            '</div>' +
            '</div>';
        itemForm += nameForm;
        itemForm += '</div>';
        $("#taskOtherItemList").append(itemForm);

        if (selectOthers.length < i + 1) {
            selectOthers[i] = i;
        }
        form.render();

    }

    function addTaskMaterielItem(index, value, number) {
        var i = selectMaterials.length;
        if (index !== null) {
            i = index;
        }
        if (number === null) {
            number = 0;
        }
        var selectClassName = 'materiel_name_' + i + '_day';
        var numberClass = 'materiel_number_' + i + '_day';
        var unitClass = 'materiel_unit_' + i + '_day';

        var itemForm = '<div class="layui-col-md12">';
        var nameForm = '<div class="layui-inline layui-col-md4">' +
            '<label class="layui-form-label">物料</label>' +
            '<div class="layui-input-block" style="line-height: 38px">' +
            '<input  type="hidden" class="layui-input"> ' +
            '<select  id=' + selectClassName + ' lay-filter=' + selectClassName + '>' +
            '</select>' +
            '</input>' +
            '</div>' +
            '</div>';

        var numberForm = '<div class="layui-inline layui-col-md4"><label class="layui-form-label">数量(斤)</label>' +
            '<div class="layui-input-block">' +
            '<input id= ' + numberClass + ' name=' + numberClass + ' type="text" value=' + number + ' class="layui-input"/>' +
            '</div>' +
            '</div>';
        itemForm += nameForm;
        itemForm += numberForm;
        itemForm += '</div>';
        $("#taskMaterielItemList").append(itemForm);

        //重新加载
        reloadTaskMaterielItem(selectClassName, i, value);
        form.render();

    }

    function reloadTaskMaterielItem(selectClassName, index, selectValue) {

        var selectItem = $("#" + selectClassName);
        $(selectItem).html('');
        if (materialList !== undefined) {
            for (var i = 0; i < materialList.length; i++) {
                var item = materialList[i];
                var desc = item.name + ' 规格:' + item.specs + item.unit;
                var value = item.value + '';

                var selected = '';
                if (selectValue !== null && selectValue === value) {
                    selected = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectValue) && value !== selectValue) {
                    selected = 'selected';
                    if (selectMaterials.length === 0) {
                        selectMaterials.push(selectValue);
                    }
                }

                $(selectItem).append('<option value="' + value + '"  ' + selected + '>' + desc + '</option>');
            }
        }
        form.on('select(' + selectClassName + ')', function (data) {
            var materielId = data.value;
            selectMaterials[index] = materielId;
        });
    }


    //表单提交事件
    function buildRequest() {
        if (Feng.isUndefined(selectWorker)) {
            Feng.error("执行人都不能为空");
            return false;
        }
        if (Feng.isUndefined(selectReviewWorker)) {
            Feng.error("审核人都不能为空");
            return false;
        }

    }

    form.on('submit(btnSubmit)', function (data) {

        var result = buildRequest();
        if (result === false) {
            return;
        }

        data.field.worker = selectWorker;
        data.field.reviewWorker = selectReviewWorker;

        var ajax = new $ax(Feng.ctxPath + "/api/taskRecord/editItem", function (data) {
            Feng.success("更新成功！");
            window.location.reload();
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });

    //==== 动作
    $("#recordButton").click(function () {

        var taskParam = "";
        if (!Feng.isUndefined(Feng.getUrlParam("taskId"))) {
            taskParam = '?taskId=' + Feng.getUrlParam("taskId");
        }
        func.open({
            title: '任务记录列表',
            content: Feng.ctxPath + '/api/taskRecord' + taskParam,
            type: 2,
            area: ["1200px", "1200px"]

        });
    });


    //返回按钮
    $("#backupPage").click(function () {

        window.location.href = Feng.ctxPath + '/api/task'
    });


});